# coding: utf-8
# 18-11-16 下午7:23
from usercenter.models import CustomerProfile
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from .token import decode_token
import hashlib
from django.conf import settings


def get_customer_user(wechat_openid='', cellphone='', email='', qq_openid=''):
    '''
        根据条件查找用户
    :param wechat_openid:
    :param cellphone:
    :param email:
    :param qq_openid:
    :return:
    '''

    query = {'wechat_openid': wechat_openid,
             'cellphone': cellphone,
             'email': email,
             'qq_openid': qq_openid}
    query = {k: v for k, v in query.items() if v}
    if not query:  # 没有查询条件， 返回空
        return None
    return CustomerProfile.objects.filter(**query).first()


def get_user_by_id(id):
    '''
    返回用户
    :param id:
    :return:
    '''

    return CustomerProfile.objects.filter(id=id).first()


def get_user_info(id, type=0):
    '''
    返回用户指定的信息
    :param id:
    :return:
    '''
    keys = ['username', 'email', 'cellphone', 'status']
    if type == 1:  # 全部返回
        keys = []
    res = CustomerProfile.objects.filter(id=id).values(*keys)
    return res[0] if res else {}


def create_customer_user(user_info):
    '''

    :return:
    '''
    return CustomerProfile.objects.create(**user_info)


def get_user_from_request(request):
    '''
    :return
    :param request:
    :return:
    {
        'user_id': user.pk,
        'email': user.email,
        'username': username,
        'exp': ''
    }
    '''
    token = JSONWebTokenAuthentication().get_jwt_value(request)
    if not token:
        return
    return decode_token(token)


def get_password_hash(password):
    '''
    get password_hash
    :param password:
    :return:
    '''
    return hashlib.md5((password + settings.SECRET_KEY).encode()).hexdigest()
